package com.atzly.community.config;

import com.atzly.community.quartz.AlphaJob;
import com.atzly.community.quartz.CalculationPostScoreJob;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

/**
 * @author zlysimida
 * @date 2021/9/4 - 9:20
 */
// 配置 -> 数据库 -> 调用
@Configuration
public class QuartzConfig {

    // 刷新间隔5分钟
    private static final long REFRESH_TIME = 1000 * 60 * 5;
    // FactoryBean可简化Bean的实例化过程:
    // 1.通过FactoryBean封装Bean的实例化过程.
    // 2.将FactoryBean装配到Spring容器里.
    // 3.将FactoryBean注入给其他的Bean.
    // 4.该Bean得到的是FactoryBean所管理的对象实例.

    // 配置JobDetail
    // @Bean
    public JobDetailFactoryBean jobDetailFactoryBean() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(AlphaJob.class);
        factoryBean.setBeanName("alphaJob");
        factoryBean.setGroup("alphaJobGroup");
        // 是否保存任务
        factoryBean.setDurability(true);
        // 是否可以回复任务
        factoryBean.setRequestsRecovery(true);
        return factoryBean;
    }

    // 配置Trigger(SimpleTriggerFactoryBean, CronTriggerFactoryBean)
    // @Bean
    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetail jobDetailFactoryBean) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(jobDetailFactoryBean);
        factoryBean.setName("alphaTrigger");
        factoryBean.setGroup("alphaTriggerGroup");
        // 每三秒触发一次AlphaJob任务
        factoryBean.setRepeatInterval(3000);
        factoryBean.setJobDataMap(new JobDataMap());
        return factoryBean;
    }

    // 设置写入数据库村塾
    @Bean
    public JobDetailFactoryBean postScoreRefreshJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(CalculationPostScoreJob.class);
        factoryBean.setBeanName("postScoreJob");
        factoryBean.setGroup("postScoreJobGroup");
        factoryBean.setDurability(true);
        factoryBean.setRequestsRecovery(true);
        return factoryBean;
    }

    // 设置触发器
    @Bean
    public SimpleTriggerFactoryBean postScoreRefreshJobTrigger(JobDetail postScoreRefreshJobDetail) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(postScoreRefreshJobDetail);
        factoryBean.setBeanName("postScoreTrigger");
        factoryBean.setGroup("postScoreTriggerGroup");
        factoryBean.setRepeatInterval(REFRESH_TIME);
        factoryBean.setJobDataMap(new JobDataMap());
        return factoryBean;
    }
}
